//
//  TTMusicAVPlayer.m
//  TTMusic
//
//  Created by 马金晖 on 16/4/7.
//  Copyright © 2016年 cpy. All rights reserved.
//

#import "TTMusicAVPlayer.h"

@implementation TTMusicAVPlayer


+(instancetype)shareTTMusicAVPlayer {
    static TTMusicAVPlayer *player = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        player = [[TTMusicAVPlayer alloc]init];
        
        player.videoProgress = [[UIProgressView alloc]init];
        
    });
    return player;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        self.style = 0;
        self.isPlay = YES;
        self.isRoration = YES;
        self.isCurrent = YES;
        self.isCurrentSong = YES;
    }
    return self;
}
#pragma mark - 播放方法
- (void)playWithURL:(CPYSONGSModel *)songListModel {
       if (self.currentItem) {
        [self replaceCurrentItemWithPlayerItem:self.currentItem];
        
    }
    self.songsModel = songListModel;
    self.songDetailModel = songListModel.songs[self.local];
    if (_songDetailModel.urlList.count != 0) {
        CPYDiscoveryPageUrlListModel *urlModel = _songDetailModel.urlList[0];
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:urlModel.url]];
        [self replaceCurrentItemWithPlayerItem:playerItem];
    }else if (_songDetailModel.auditionList.count != 0) {
        CPYDiscoveryPageAuditionListModel *auditionListModel = _songDetailModel.auditionList[0];
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:auditionListModel.url]];
        [self replaceCurrentItemWithPlayerItem:playerItem];
    } else {
        
    }
    [TTMusicPlayBottomView playBottomView].songsModel = songListModel;
    [TTMusicSinglePlayerViewController sharePlayViewController].songsModel = songListModel;
//   监听播放的NSTimer
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
    if (_isCurrentSong == YES) {
        _isCurrentSong = NO;
    }
    [self play];
}
#pragma mark - timer的事件
- (void)updateSlider {
    switch (_style) {
        case 0:
            if (CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.currentTime) / CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.duration) == 1) {
                _local += 1;
                _songDetailModel = _songsModel.songs[_local];
                [self customPlay];
            }
            break;
        case 1:
            if (CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.currentTime) / CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.duration) == 1) {
                _songDetailModel = _songsModel.songs[_local];
                [self customPlay];
            }
            break;
        case 2:
            if (CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.currentTime) / CMTimeGetSeconds([TTMusicAVPlayer shareTTMusicAVPlayer].currentItem.duration) == 1) {
                _songDetailModel = _songsModel.songs[arc4random()%_songsModel.songs.count];
                [self customPlay];
            }
            break;
        default:
            break;
    }
}
#pragma mark - 自定义的播放方法，内部用，外部不用
- (void)customPlay {
    if (self.currentItem) {
        
        
        [self replaceCurrentItemWithPlayerItem:self.currentItem];
    }
    CPYDiscoveryPageUrlListModel *urlModel = _songDetailModel.urlList[0];
    AVPlayerItem *playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:urlModel.url]];
    [self replaceCurrentItemWithPlayerItem:playerItem];
    [TTMusicPlayBottomView playBottomView].songsModel = _songsModel;
    [self play];
}
/**
 *  下一曲
 */
- (void)nextMusic {
    switch (_style) {
        case REPEATONE:
            if (self.songsModel) {
                if (self.local == self.songsModel.songs.count - 1) {
                    self.local = 0;
                    [self customPlay];
                } else {
                    self.local += 1;
                    [self customPlay];
                }
            }
            if (self.songsModel != nil) {
                if (self.local == self.songsModel.songs.count - 1) {
                    self.local = 0;
                    [self customPlay];
                } else {
                    self.local += 1;
                    [self customPlay];
                }
            }
            break;
        case ORDERPLAY:
            if (self.songsModel) {
                if (self.local == self.songsModel.songs.count - 1) {
                    self.local = 0;
                    [self customPlay];
                } else {
                    self.local += 1;
                    [self customPlay];
                }
            }
            break;
        case ARCPLAY:
            if (self.songsModel) {
                self.local = arc4random()%(self.songsModel.songs.count - 1);
                [self customPlay];
            }
            break;
        default:
            break;
    }
    _isPlay = YES;
}
/**
 *  上一曲
 */
- (void)frontMusic {
    switch (_style) {
        case REPEATONE:
            if (self.songsModel) {
                if (self.local ==0) {
                    self.local =  self.songsModel.songs.count - 1;
                    [self setUrlListModel];
                } else {
                    self.local -= 1;
                    [self setUrlListModel];
                }
            }
            break;
        case ORDERPLAY:
            if (self.songsModel) {
                if (self.local ==0) {
                    self.local =  self.songsModel.songs.count - 1;
                    [self setUrlListModel];
                } else {
                    self.local -= 1;
                    [self setUrlListModel];
                }
            }
            break;
        case ARCPLAY:
            if (self.songsModel) {
                self.local = arc4random()%(self.songsModel.songs.count - 1);
                [self setUrlListModel];
            }
            break;
        default:
            break;
    }
    _isPlay = YES;
}
- (void)setUrlListModel {
    if (self.songsModel) {
        self.songDetailModel = self.songsModel.songs[self.local];
        if (self.songDetailModel.urlList.count != 0) {
//            CPYDiscoveryPageUrlListModel *urlModel = self.songDetailModel.urlList[0];
//            [self playWithUrl:self.songsModel];
            [self play];
        } 
    }
}
/**
 *  下一曲
 */
#pragma mark - 视频的播放方法
-(void)playWithMVURL:(NSString *)url {
    
    
    if (_isCurrent == NO) {
//        [self replaceCurrentItemWithPlayerItem:self.currentItem];
        
        [self.playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        _isCurrent = YES;
    }
    self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
//    [self customPlay];
    
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];// 监听loadedTimeRanges属性
    if (_isCurrent == YES) {
        _isCurrent = NO;
    }
    
    [self replaceCurrentItemWithPlayerItem:self.playerItem];

    self.isPlay = YES;
}



#pragma mark - 缓存的KVO（属性监听）
// KVO方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    
    
    
    AVPlayerItem *playerItem = (AVPlayerItem *)object;
//    if ([keyPath isEqualToString:@"loadedSongTimeRanges"]) {
//        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
//        NSLog(@"Time Interval:%f",timeInterval);
//        CMTime duration = _playerItem.duration;
//        CGFloat totalDuration = CMTimeGetSeconds(duration);
//        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
//    }
    
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeInterval = [self availableDuration];// 计算缓冲进度
//        NSLog(@"Time Interval:%f",timeInterval);
        CMTime duration = _playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.videoProgress setProgress:timeInterval / totalDuration animated:YES];
    }
}
- (NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[self.playerLayer.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;// 计算缓冲总进度
    return result;
}

- (void)changeStyle{
    switch (_style) {
        case REPEATONE:
            _style = ORDERPLAY;
            break;
        case ORDERPLAY:
            _style = ARCPLAY;
            break;
        case ARCPLAY:
            _style = REPEATONE;
            break;
        default:
            break;
    }
}
- (void)pause {
    [super pause];
    _isPlay = NO;
    _isRoration = NO;
    self.isPlay = NO;
}
- (void)play {
    [super play];
    _isPlay = YES;
    _isRoration = YES;
}

@end
